package com.jxk.security.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jxk.security.entity.User;
import com.jxk.security.mapper.RoleMapper;
import com.jxk.security.mapper.UrMapper;
import com.jxk.security.mapper.UserMapper;
import com.jxk.security.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jxk
 * @since 2020-10-25
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    RoleMapper roleMapper;
    @Autowired
    UrMapper urMapper;
    @Override
    public User getUser(String name) {
        QueryWrapper<User> wrapper=new QueryWrapper();
        wrapper.select("name","password").eq("name",name);
        User user=userMapper.selectOne(wrapper);
        //2.加载用户角色列表
        List<String> roleCodes = userMapper.findRoleByUserName(name);
        //3.通过用户角色列表加载用户的资源权限列表
        List<String> authority = userMapper.findAuthorityByRoleCodes(roleCodes);
        List<String> roleList=new ArrayList<>();
        for (String roleCode : roleCodes) {
          roleCode="ROLE_"+roleCode;
          roleList.add(roleCode);
        }
        //4.添加修改好前缀的角色前缀的角色权限
        authority.addAll(roleList);
        user.setAuthorities( AuthorityUtils.commaSeparatedStringToAuthorityList(
                //List转字符串,逗号分隔
                String.join(",",authority)
        ));
        return user;
    }
}
